﻿using SearchStarPlus.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;

namespace SearchStarPlus.Controllers
{
    public class ArticleUIController : Controller
    {
        //
        // GET: /ArticleUI/

        public ActionResult Index()
        {
            return View();
        }

        private string apiUrl = "";
        HttpClient client = new HttpClient();

        public ArticleUIController(string baseUrl, string apiUrl)
        {
            this.apiUrl = apiUrl;
            this.client.BaseAddress = new Uri(baseUrl);
            this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        // need to figure out utf-8 encoding

        public List<Article> Get()
        {
            HttpResponseMessage response = client.GetAsync(this.apiUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var articles = response.Content.ReadAsAsync<IEnumerable<Article>>().Result;
                return articles.ToList();
            }
            else
            {
                return null;
            }
        }

        public List<Article> SearchArticles(List<String> terms)
        {
            HttpResponseMessage response = client.GetAsync(this.apiUrl).Result;
            
            if (response.IsSuccessStatusCode)
            {
                var articles = response.Content.ReadAsAsync<IEnumerable<Article>>().Result;

                //var terms = q.Trim().Split(' ');
                articles = from a in articles
                           where terms.Any(s => a.Text.Contains(s))
                           select a;

                foreach (var item in articles)
                {
                    foreach (var word in terms)
                    {
                        item.Text = item.Text.Replace(word, "<span class='highlight'>" + word + "</span>");
                    }
                }

                return articles.ToList();
            }
            else
            {
                return null;
            }
        }

    }
}
